package com.yqg.education.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yqg.education.controller.dto.ImportQuestionDto;
import com.yqg.education.controller.dto.ImportUserDto;
import com.yqg.education.entity.*;
import com.yqg.education.mapper.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * projectName:xf-service1
 * author:zxf
 * time:2024/10/15 9:49
 * description:
 */
@Component
public class UserListener extends AnalysisEventListener<ImportUserDto> {

    @Resource
    private UserMapper userMapper;

    @Resource
    private TrainClassMapper trainClassMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private ClassStudentMapper classStudentMapper;

    @Override
    public void invoke(ImportUserDto importUserDto, AnalysisContext analysisContext) {
        if (importUserDto.getTelephone() == null || importUserDto.getTelephone().equals("") || importUserDto.getClassId() == null) {
            return;
        }
        TrainClass trainClass = trainClassMapper.selectById(importUserDto.getClassId());
        if (trainClass == null) {
            return;
        }
        User user = new User();
        BeanUtil.copyProperties(importUserDto, user, true);
        user.setPassword(SecureUtil.md5("123456"));
        user.setCreateTime(LocalDateTime.now());
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getTelephone, user.getTelephone());
        List<User> userList = userMapper.selectList(userLambdaQueryWrapper);
        if (userList != null && userList.size() > 0) {
            return;
        }
        userMapper.insert(user);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(4l);
        userRoleMapper.insert(userRole);
        ClassStudent classStudent = new ClassStudent();
        classStudent.setStuId(user.getId());
        classStudent.setClassId(importUserDto.getClassId());
        classStudentMapper.insert(classStudent);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
